package spring.cloud.tasks.executor.executor.task.task_configuration;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import spring.cloud.tasks.executor.executor.task.TreeCacheListener;

/**
 * 任务删除
 */
@Slf4j
@Setter
@Getter
public class DeleteTaskListener extends TreeCacheListener {

    private final TaskConfigurationListenerHolder taskConfigurationListenerHolder;

    public DeleteTaskListener(TaskConfigurationListenerHolder taskConfigurationListenerHolder) {
        this.taskConfigurationListenerHolder = taskConfigurationListenerHolder;
    }

    @Override
    protected void dataChanged(CuratorFramework curatorFramework, String path, TreeCacheEvent treeCacheEvent) {
        if (taskConfigurationListenerHolder.isShutdown) {
            return;
        }
        if ((TaskConfigurationNode.isDeletePath(taskConfigurationListenerHolder.taskId, path) || TaskConfigurationNode.isToDeletePath(taskConfigurationListenerHolder.taskId, path)) && //
                (TreeCacheEvent.Type.NODE_ADDED == treeCacheEvent.getType() || TreeCacheEvent.Type.NODE_UPDATED == treeCacheEvent.getType())) {
            Thread thread = new Thread(new Runnable() {
                //
                @Override
                public void run() {
                    try {
                        taskConfigurationListenerHolder.taskExecutor.shutdown();
                    } catch (Throwable t) {
                        log.info("停止任务执行器失败:" + taskConfigurationListenerHolder.taskId, t);
                    }
                }
            });
            thread.setName(taskConfigurationListenerHolder.executorId + "-" + taskConfigurationListenerHolder.taskId + "-taskDelete");
            thread.start();
        }
    }
}
